package com.gopay.scheduler.job;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.rims.RimsStatus;
import com.gopay.common.constants.rims.RimsTxnCd;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.rims.RimsConfirmParas;
import com.gopay.common.domain.rims.RimsConfirmResult;
import com.gopay.common.domain.rims.RimsTmsEvaluateLog;
import com.gopay.common.rcs.dao.rims.RimsTmsEvaluateLogDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.cps.rims.RimsRemoteService;
import com.gopay.scheduler.GopayBaseJob;

/**
 * 
 * 外部风控交易确认定时任务
 * 
 * @RimsTranRiskConfirmJob.java
 * @author MA HUAN
 * @2014-11-24 下午2:44:43  www.gopay.com.cn Inc.All rights reserved.
 */
public class RimsTranRiskConfirmJob extends GopayBaseJob {
    
    private Logger logger = LoggerFactory.getLogger(RimsTranRiskConfirmJob.class);
    
    private static final int DELAY_MINUTES = -6 * 60;//6小时前
    private static final int MAX_CONFIRM_COUNT = 10; //最多上报10次

    @Resource(name = "rimsTmsEvaluateLogDAO")
    private RimsTmsEvaluateLogDAO rimsTmsEvaluateLogDAO;
    
    @Resource(name = "cpsGeneralMainOrderQueryDAO")
    private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderQueryDAO;
    
    @Resource(name = "rimsService")
    private RimsRemoteService rimsService;
    
    @Override
    public void doJobInternal() {
        Date dateBefore = DateUtils.add(new Date(), Calendar.MINUTE, DELAY_MINUTES);
       
        
        int confirmedCount = 0;
        int cleanedCount = 0;
        int overConfirmCount = 0;
        try {
          //加载风险识别成功的日志
          List<RimsTmsEvaluateLog> logs = rimsTmsEvaluateLogDAO.listByRimsStatusAndTime(RimsStatus.RIMS_STATUS_01, dateBefore);
          logger.info("Load {} RimsTmsEvaluateLog(RimsStatus["+RimsStatus.RIMS_STATUS_01.value()+"]) by Params[dateBefore:{}]", logs == null ? "0" : logs.size(), dateBefore);
          
          if(logs != null && !logs.isEmpty()) {
              for(RimsTmsEvaluateLog log : logs) {
                //检查日志对应的国付宝交易的交易结果，并将结果上报
                  if(isNeedCronConfirm(log)) {
                      CpsGenMainOrder order = cpsGeneralMainOrderQueryDAO.find(CpsGenMainOrder.class, log.getRimsTranOrder());
                      if(order != null) {
                          boolean confirmed = riskConfirm(log, order);
                          if(confirmed) {
                              log.setRimsStatus(RimsStatus.RIMS_STATUS_02.value());
                              
                              ++ confirmedCount;
                          }
                          else if((log.getRimsConfirmCount() + 1) >= MAX_CONFIRM_COUNT){
                              log.setRimsStatus(RimsStatus.RIMS_STATUS_98.value());
                              
                              ++ overConfirmCount;
                          }
                          
                      }
                  }
                  else {
                      log.setRimsStatus(RimsStatus.RIMS_STATUS_99.value());
                      
                      ++ cleanedCount;
                  }
                  
                  //更新日志
                  log.setRimsConfirmCount(log.getRimsConfirmCount() + 1);
                  log.setRimsLastConfirmTime(new Date());
                  rimsTmsEvaluateLogDAO.update(log);
              }
          }
        }
        catch(Exception e) {
            logger.error("RimsTranRiskConfirmJob------Error!------， DateBefore:{}", dateBefore, e); 
        }
        
       
    }
    
    
    /**
     * 是否需要按照国付宝交易结果确认
     * @param log
     * @return
     */
    private boolean isNeedCronConfirm(RimsTmsEvaluateLog log) {
        
        if(     //如果是登录日志，则不需要定时上报结果，登录结果采用即时上报的方式
                log.getRimsTranCode().equals(IntTxnCd._00001.value) ||
                //如果是大宗签约、解约采用即时上报确认信息，不需要定时上报
                log.getRimsTranCode().equals(IntTxnCd._00203.value) ||
                //如果是大宗签约、解约采用即时上报确认信息，不需要定时上报
                log.getRimsTranCode().equals(IntTxnCd._00204.value) ||
                //如果是大宗签到、签退采用即时上报确认信息，不需要定时上报
                log.getRimsTranCode().equals(IntTxnCd._00205.value) ||
                //如果是大宗签到、签退采用即时上报确认信息，不需要定时上报
                log.getRimsTranCode().equals(IntTxnCd._00206.value) ||
                //如果是P2P绑定、解绑，采用即时上报确认信息，不需要定时上报
                log.getRimsTranCode().equals(IntTxnCd._01304.value) ||
                //如果是P2P绑定、解绑，采用即时上报确认信息，不需要定时上报
                log.getRimsTranCode().equals(IntTxnCd._01305.value)
                ) {
             return false;
        }
        return true;
    }
    
    private String getRimsTranTxnCd(int txnStaCd) {
        if(TxnStaCode.TXN_STA_CD_20000.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_20000.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_20001.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_20001.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_20002.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_20002.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_20003.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_20003.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_30000.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_30000.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_30101.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_30101.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_30102.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_30102.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_90000.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_90000.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_90001.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_90001.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_90002.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_90002.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_90101.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_90101.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_90102.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_90102.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_90201.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_90201.value();
        }
        
        if(TxnStaCode.TXN_STA_CD_90301.value == txnStaCd) {
            return RimsTxnCd.TXN_CD_90301.value();
        }
        
        return RimsTxnCd.TXN_CD_99999.value();
    }

    private boolean riskConfirm(RimsTmsEvaluateLog log, CpsGenMainOrder order) {
        try {
            RimsConfirmParas paras = new  RimsConfirmParas();
            
            paras.putPara(RimsConfirmParas.ParaKey.CUST_NO, log.getRimsCustNo());
            paras.putPara(RimsConfirmParas.ParaKey.TRANS_ORDER_ID, log.getRimsTranOrder());
            paras.putPara(RimsConfirmParas.ParaKey.TRANS_STATUS, getRimsTranTxnCd(order.getTxnStaCd()));
            
            RimsConfirmResult result = rimsService.riskConfirm(log.getRimsTranCode(), paras);
            
            return (result != null && result.isSucceed());
        }
        catch(Exception e) {
            logger.error("RimsTranRiskConfirmJob------call remote:riskConfirm() Error------", e);
        }
        
        return false;
    }
}
